import { getToken } from '@/utils/auth';
import { ElNotification } from 'element-plus';
import useNoticeStore from '@/store/modules/notice';
import { UseWebSocketOptions } from '../types/useWebSocket.d.ts';

// 初始化socket
export const initWebSocket = (url: any, onMessageCallback?: (message: any) => void) => {
  if (import.meta.env.VITE_APP_WEBSOCKET === 'false') {
    return;
  }
  url = url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID;
  const options: UseWebSocketOptions = {
    autoReconnect: {
      retries: 3,
      delay: 1000,
      onFailed() {
        console.log('websocket重连失败');
      }
    },
    heartbeat: {
      message: JSON.stringify({ type: 'ping' }),
      interval: 10000,
      pongTimeout: 2000,
      onSend() {
        console.log('发送心跳消息');
      },
      onReceive() {
        console.log('收到心跳响应');
      }
    },
    onConnected() {
      console.log('websocket已经连接');
    },
    onDisconnected() {
      console.log('websocket已经断开');
    },
    onMessage: (ws: WebSocket, event: MessageEvent<any>) => {
      if (event.data === 'ping') {
        console.log('收到心跳响应');
        return;
      }
      useNoticeStore().addNotice({
        message: event.data,
        read: false,
        time: new Date().toLocaleString()
      });
      if (onMessageCallback) {
        onMessageCallback(event.data);
      }
    },
    // 调整 onError 回调函数以匹配新的类型定义
    onError: (ws: WebSocket, event: Event) => {
      console.log('WebSocket 连接出错:', event);
    }
  };
  useWebSocket(url, options);
};
